package com.wzl.demo_08_05_client;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcelable;
import android.os.RemoteException;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private Intent intent;
    Messenger m;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent = new Intent("com.demo.demo_08_05_server.MyService");
        intent.setPackage("com.wzl.demo_08_05_server");
    }

    public void bind(View view) {
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
    public void unbind(View view) {
        unbindService(conn);
    }
    public void send(View view){
        /*报错
         * Can't marshal non-Parcelable objects across processes.
         *
         * obj应该是一个实现了Parcelable接口的对象.
         * */
        Message obtain = Message.obtain();
        obtain.what = 1;
        obtain.arg1 = 2;
        obtain.arg2 = 3;
        obtain.obj = new Parcelable() {
            @Override
            public int describeContents() {
                return 0;
            }
            @Override
            public void writeToParcel(android.os.Parcel dest, int flags) {}
        };
        try {
            m.send(obtain);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }


    }


    // 连接服务
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("onServiceConnected");
            m = new Messenger(service);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("onServiceDisconnected");
        }
    };

}